package com.maint.m

import android.app.Application
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.ViewModelProvider
import com.maint.m.modle.BaseViewModel

class App : Application(), LifecycleObserver {
    // 创建BaseViewModel实例用于管理SDK初始化
    private lateinit var baseViewModel: BaseViewModel
    
    companion object {
        lateinit var instance: App
        private set
    }
    
    override fun onCreate() {
        super.onCreate()
        instance = this
        // 注册应用生命周期观察者
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
        
        // 初始化BaseViewModel
        baseViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
            .create(BaseViewModel::class.java)
        
        // 调用SDK初始化方法
        baseViewModel.initSDK()
        Log.d("AppInit", "SDK初始化完成")
    }

    // 当应用进入后台（所有Activity都不可见）
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackground() {
        // 在应用进入后台时断开WebSocket连接
        WebSocketManager.getInstance().disconnect()
        Log.d("WebSocket", "应用进入后台，断开连接")
    }

    // 当应用回到前台
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForeground() {
        // 应用回到前台时重新连接WebSocket
        val webSocketService = WebSocketService.getInstance()
        if (!webSocketService.isConnected()) {
            webSocketService.connect()
            Log.d("App", "应用回到前台，重新连接WebSocket")
        }
    }

    // 监听应用进程终止
    override fun onTerminate() {
        super.onTerminate()
        WebSocketManager.getInstance().disconnect()
        // 在应用终止时调用SDK的销毁方法释放资源
        if (::baseViewModel.isInitialized) {
            baseViewModel.destroySDK()
            Log.d("AppInit", "SDK资源已释放")
        }
        Log.d("WebSocket", "应用终止，断开连接")
    }
}